import redis
import threading
import time
 
# Redis 配置（与你的 docker-compose.yaml 一致）
REDIS_HOST = "localhost"
REDIS_PORT = 6380
REDIS_PASSWORD = "mhSCk0NheGhmtsha"  # 替换为你的密码
POOL_SIZE = 50  # 连接池大小
TEST_COUNT = 100  # 测试请求次数

# 创建 Redis 连接池
pool = redis.ConnectionPool(
    host=REDIS_HOST,
    port=REDIS_PORT,
    password=REDIS_PASSWORD,
    max_connections=POOL_SIZE,
    socket_timeout=5,
    decode_responses=True,
)

def test_redis_connection():
    try:
        r = redis.Redis(connection_pool=pool)
        r.ping()  # 测试连接
        r.set("test_key", "test_value")  # 写入测试数据
        val = r.get("test_key")  # 读取测试数据
        print(f"Success: {val}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    start_time = time.time()

    # 模拟并发请求
    threads = []
    for i in range(TEST_COUNT):
        t = threading.Thread(target=test_redis_connection)
        threads.append(t)
        t.start()

    # 等待所有线程完成
    for t in threads:
        t.join()

    end_time = time.time()
    print(f"Test completed in {end_time - start_time:.2f} seconds")